<template>
    <div style="height: 100%; position: relative">
        <el-drawer
            :title="title"
            :before-close="handleClose"
            :visible.sync="show_dialog"
            direction="rtl"
			size="60%"
            custom-class="demo-drawer"
            ref="drawer">
            <div class="demo-drawer__content">
                <el-form :model="form" ref="form" :label-width="formLabelWidth" size="mini" :rules="rules">
                    <el-form-item
                        label="积分充值类型"
                        prop="points_model">
                        <el-select
                            v-model="form.points_model"
                            placeholder="请选择积分充值类型">
                            <el-option label="预充值模式" value="1"></el-option>
                            <el-option label="后结算模式" value="2"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="店铺名称" prop="store_name">
                        <el-col :span="14">
                            <el-input v-if="item_data" v-model="form.store_name" placeholder="请选择店铺" @click.native="showStoreBox=true"></el-input>
		                    <store-list :showStoreBox.sync="showStoreBox" @chooseStore="getStoreInfo"></store-list>
                        </el-col>
                    </el-form-item>
                    <el-form-item label="商家购买金额" prop="amount">
                        <el-col :span="14">
                            <el-input v-model.number="form.amount" autocomplete="off" @input="handleAmoutInput" maxlength="10"></el-input>
                        </el-col>
                        <el-col :span="6" class="el-form-desc">万元</el-col>
                    </el-form-item>
                    <el-form-item label="积分赠送比" prop="points_ratio">
                        <el-col :span="14">
                            <el-input v-model="form.points_ratio" autocomplete="off">
                            </el-input>
                        </el-col>
                        <el-col :span="8" class="el-form-desc">车家佳赠送积分/商家购买积分</el-col>
                    </el-form-item>
                    <el-form-item label="选择时间" prop="addTime">
                        <el-date-picker
                            v-model="form.addTime"
				        	value-format="yyyy-MM-dd"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="配置类别" prop="config_type">
                        <el-col :span="14">
                            <el-input v-model="form.config_type" autocomplete="off"></el-input>
                        </el-col>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="closeDrawer">取 消</el-button>
                        <el-button type="primary" @click="submitForm" :loading="loading"
                            >{{ loading ? "提交中 ..." : "确 定" }}</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-drawer>
        <sms-verification :options="smsDialogOptions" @update="smsDialogUpdate"></sms-verification>
    </div>
</template>
<script>
import storeList from "@/components/home/store-list.vue";
import { dateFormatter, filterNumber } from "@/common/js/util"
import SmsVerification from "@/components/home/sms-verification.vue";
export default {
    components: { storeList, SmsVerification },
    data() {
        const validateAmount = (rule, value, callback) => {
            if (+value > this.form.amounted) {
                callback(new Error("购买金额不可超过剩余可发放积分"));
            } else {
                callback();
            }
        }
        return {
            loading: false,
            form: {
                id:'',
                points_model: '',
                amount: '',
                points_ratio: '',
                addTime: '',
                config_type: '',
                store_name: '',
                addTime: []
            },
            formLabelWidth: '110px',
            timer: null,
            showStoreBox:false,
			show_dialog:false,
            type:'add',///新增
            props: ['storeInfo'],
            item_data:'',
            title: '新增配置',
            rules: {
                points_model: [{required: true, message: '请选择积分充值类型', trigger: 'change'}],
                store_name: [{required: true, message: '请选择店铺名称', trigger: 'change'}],
                amount: [
                    {required: true, message: '请填写商家购买金额', trigger: 'blur'},
                    { validator: validateAmount, trigger: ["blur", "change"] }
                ],
                points_ratio: [{required: true, message: '请填写积分配送比', trigger: 'blur'}],
                addTime: [{required: true, message: '请选择时间', trigger: 'change'}],
                //config_type: [{required: true, message: '请填写配置类别', trigger: 'blur'}]
            },
            smsDialogOptions: { visible: false }
        };
	},
	created(){
        console.log('created',this)
    },
    methods: {
            ////获取单个店铺信息只需要 id和name
       getStoreInfo(storeDataInfo) {
          
           console.log('-storeDataInfo------->>>',storeDataInfo);
            this.form.store_name = storeDataInfo.storeName;
            this.item_data.store_id= storeDataInfo.storeId;
  
		},
    ////data 为上一页面带过去的
		show_dialog_fn(data) {
			if(data){
                this.form.id = data.id;
				this.item_data = Object.assign({}, data);
                if(data.id) {
                    this.title = '编辑配置';
                    this.type = 'edit'///edit
                    this.form.addTime = [
                        dateFormatter('YYYY-MM-DD', this.item_data.start_date * 1000),
                        dateFormatter('YYYY-MM-DD', this.item_data.end_date * 1000)
                    ];
                    this.form.points_model = this.item_data.points_model;
                    this.form.amount = this.item_data.amount;
                    this.form.amounted = this.item_data.amounted || 0;
                    this.form.points_ratio = this.item_data.points_ratio;
                    this.form.config_type = this.item_data.config_type;
                    this.form.store_name = this.item_data.store_name;
                } else {
                    this.title = '新增配置'
                }
			}
			this.show_dialog = true;
		},
        handleClose(done) {
            this.$confirm('确定要关闭表单吗？')
            .then(() => {
                this.closeDrawer();
            })
            .catch(() => { });
        },
        smsDialogUpdate(res) {
            this.submitForm({ verified: true })
        },
        submitForm(obj) {
            if (this.loading) {
                return;
            }
            this.$refs.form.validate(valid => {
                if (valid) {
                    if (!obj.verified) {
                      this.smsDialogOptions = { visible: true, type: 3 }
                      return
                    }
                    this.conformFun().then(() =>{})
                    // this.$confirm('确定要提交表单吗？')
                    // .then(_ => {
                        // this.loading = true;
                        // this.timer = setTimeout(() => {
                        //     this.conformFun().then(() =>{
                        //     })
                          
                        //     // 动画关闭需要一定的时间
                        //     setTimeout(() => {
                        //         // console.log(this.$parent)
                        //         // this.$parent.getList();
                        //         this.loading = false;
                        //     }, 400);
                        // }, 2000);
                    // }).catch(_ => { });
                } else {
                    //this.$message.error('请检查必填项')
                }
            })
        },
        closeDrawer() {
            this.loading = false;
			this.show_dialog = false;
            clearTimeout(this.timer);
            this.$refs.form.resetFields();
            this.form.points_model = '';
            this.form.amount = '';
            this.form.points_ratio = '';
            this.form.config_type = '';
            this.form.store_name = '';
            this.form.addTime = [];
        },
        conformFun(){
            const data = {};
            data.id = this.form.id;
            data.points_model = this.form.points_model;
            data.amount = this.form.amount;
            data.points_ratio = this.form.points_ratio;
            data.config_type = this.form.config_type;
            data.store_name = this.form.store_name;
            data.store_id = this.item_data.store_id;

            //console.log('xxxxxxxxxxxxxxx--data--xxxxxxxxxxxxxx',data);
			if (this.form.addTime) {
                // const endAddMS = this.form.addTime[1].getTime();
				// const startAddMS = this.form.addTime[0].getTime();
				
				// if (startAddMS == endAddMS) {
				// 	data.start_date = dateFormatter('YYYY-MM-DD hh:mm:ss', startAddMS);
				// 	data.end_date = dateFormatter('YYYY-MM-DD hh:mm:ss', endAddMS + (24 * 60 * 60 - 1) * 1000);
                // } else {
					data.start_date = dateFormatter('YYYY-MM-DD 00:00:00', this.form.addTime[0]);
					data.end_date = dateFormatter('YYYY-MM-DD 23:59:59', this.form.addTime[1]);
                // }
            }
			return this.$http.post('/admin/points/index.php?act=points_config&op=addOrEdit', data).then(res => {
				if (res.code == 1) {
                    this.$message({
                        showClose: true,
                        message: res.msg,
                        type: "success"
                    });
                    this.$emit("getList")
                    this.closeDrawer()
				}else {
					alert(res.msg);
				}
			})  
        },
        handleAmoutInput(val) {
            this.form.amount = filterNumber(val, 4)
        }
    }
};
</script>
<style lang="scss" scoped>
    .el-form{ 
        padding: 10px 40px;
        max-width: 800px;
        .el-form-desc {
            color: #999;
            font-size: 12px;
            line-height: 110%;
            display:flex;
            align-items: center;
            justify-content: flex-start;
            height: 27px;
            padding-left: 6px;
        }
    }
    .el-form-item label:after {
        content: "";
        display: inline-block;
        width: 100%;
    }

    .el-form-item__label {
        text-align: center;
        height: 50px;
    }
    
    .el-form-item.is-required .el-form-item__label:before {
        content: none !important;
    }
    .el-input__inner{
       min-width: 350px;
    }
</style>